package ar.com.juanlopezcervero.flexigrid4j.page;

import java.io.Serializable;
import java.util.List;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

public abstract class GridPageDTO<T> implements Serializable {

	private static final long serialVersionUID = -4126044552383508257L;

	private GridFilterDTO filter;
	
	private List<T> rows;
	private Long totalCount;
	
	
	public String generateJSON() throws JSONException {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("page", filter.getPage());
		jsonObject.put("total", this.getTotalCount());
		jsonObject.put("rows", getRowsJSON());
		return jsonObject.toString(4);
	}
	
	
	private JSONArray getRowsJSON() throws JSONException {
		JSONArray jsonRows = new JSONArray();
		for (T dto : rows) {
			JSONObject itemJson = new JSONObject();
			itemJson.put("id", getItemId(dto));
			itemJson.put("cell", getItemAsJSONArray(dto));
			jsonRows.put(itemJson);
		}
		return jsonRows;

	}

	protected abstract Integer getItemId(T dto);

	protected abstract JSONArray getItemAsJSONArray(T dto);


	public List<T> getRows() {
		return rows;
	}
	public void setRows(List<T> rows) {
		this.rows = rows;
	}
	public Long getTotalCount() {
		return totalCount;
	}
	public void setTotalCount(Long totalCount) {
		this.totalCount = totalCount;
	}


	public GridFilterDTO getFilter() {
		return filter;
	}


	public void setFilter(GridFilterDTO filter) {
		this.filter = filter;
	}
	
	
	
}
